import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  loginByPhoneService,
  registerUserService,
  getUserInfoService
} from '@/api/user'

export const useUserStore = defineStore('db_user', () => {
  // 状态
  const user = ref(null)
  const token = ref('')

  // 登录
  const login = async (phone, password) => {
    try {
      const res = await loginByPhoneService({ phone, password })
      token.value = res.data
      await getUserInfo()
      return true
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const res = await getUserInfoService()
      console.log(res)
      user.value = res.data
      return user.value
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  }

  // 注册
  const register = async (userData) => {
    try {
      await registerUserService(userData)
      return true
    } catch (error) {
      console.error('注册失败:', error)
      return false
    }
  }

  // 退出登录
  const logout = () => {
    user.value = null
    token.value = ''
  }

  return {
    user,
    token,
    login,
    getUserInfo,
    register,
    logout,
  }
}, 
{
  persist: true
})
